package com.alipay.rebate.shop.service.admin.impl;

import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.rebate.shop.constants.*;
import com.alipay.rebate.shop.dao.mapper.*;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.helper.JpushHelper;
import com.alipay.rebate.shop.helper.LuckyMoneyHelper;
import com.alipay.rebate.shop.helper.MobileCodeInformationHelper;
import com.alipay.rebate.shop.helper.UserIncomeHelper;
import com.alipay.rebate.shop.model.*;
import com.alipay.rebate.shop.pojo.alipay.TransferReq;
import com.alipay.rebate.shop.pojo.alipay.WithdrawUserInfo;
import com.alipay.rebate.shop.pojo.mobilecode.SendSmsResponse;
import com.alipay.rebate.shop.service.admin.AlipayOrderService;
import com.alipay.rebate.shop.core.AbstractService;
import com.alipay.rebate.shop.utils.AliPayUtil;
import com.alipay.rebate.shop.utils.DecimalUtil;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;

import com.alipay.rebate.shop.utils.AliUtil;
import com.aliyuncs.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


/**
 * Created by CodeGenerator on 2019/09/12.
 */
@Service
@Transactional
public class AlipayOrderServiceImpl extends AbstractService<AlipayOrder> implements AlipayOrderService {

    private Logger logger = LoggerFactory.getLogger(AlipayOrderServiceImpl.class);
    @Resource
    private AlipayOrderMapper alipayOrderMapper;
    @Resource
    private WithDrawMapper withDrawMapper;
    @Autowired
    private JpushHelper jpushHelper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private JpushSettingsMapper jpushSettingsMapper;
    @Resource
    private UserIncomeHelper userIncomeHelper;
    @Resource
    private LuckyMoneyHelper luckyMoneyHelper;
    @Resource
    private MobileCodeInformationHelper informationHelper;


    @Override
    public List<AlipayOrder> transfer(TransferReq transferReq) {

        // 是否先检查用户余额或者集分宝
        logger.debug("TransferReq is : {}",transferReq);
        checkUserAmount(transferReq);

        List<AlipayOrder> resOrders = new ArrayList();
        for (AlipayOrder alipayOrder : transferReq.getAlipayOrders()){
            try {
                String orderNo = (new Date().getTime())+ AliPayUtil.getRandomChar(5);
                WithDraw withDraw = withDrawMapper.selectByPrimaryKey(alipayOrder.getWithdrawId());
                logger.debug("WithDraw is : {}",withDraw);
                if(withDraw != null){
                    if(withDraw.getStatus()==1 || withDraw.getStatus() ==2){
                        alipayOrder.setAmount(String.valueOf(withDraw.getMoney()));
                        alipayOrder.setPayeeAccount(withDraw.getAccount());
                        alipayOrder.setPayeeRealName(withDraw.getRealName());
                        if(alipayOrder.getPayeeAccount()==null||alipayOrder.getPayeeAccount().equals("")){
                            alipayOrder.setOrderNo(orderNo);
                            alipayOrder.setResponseCode("5050");
                            alipayOrder.setResponseMsg("收款方账号不能为空");
                            alipayOrder.setCreateTime(new Date());
                        }else if(alipayOrder.getAmount()==null||alipayOrder.getAmount().equals("")){
                            alipayOrder.setOrderNo(orderNo);
                            alipayOrder.setResponseCode("5051");
                            alipayOrder.setResponseMsg("转账金额不能为空");
                            alipayOrder.setCreateTime(new Date());
                        }else if (alipayOrder.getPayeeRealName()==null||alipayOrder.getPayeeRealName().equals("")){
                            alipayOrder.setOrderNo(orderNo);
                            alipayOrder.setResponseCode("5052");
                            alipayOrder.setResponseMsg("收款方真实姓名不能为空");
                            alipayOrder.setCreateTime(new Date());
                        }else{ //转账操作
                            alipayOrder.setOrderNo(orderNo);
                            AlipayFundTransToaccountTransferResponse response = AliPayUtil.alipayTransfer(alipayOrder);
                            if(response.getCode().equals("10000")){ //修改提现表状态
                                WithDraw tempWd = new WithDraw();
                                tempWd.setWithdrawId(withDraw.getWithdrawId());
                                tempWd.setHandleTime(new Date());
                                tempWd.setStatus(2);
                                userIncomeHelper.updateUserIncome(withDraw.getUserId(),2);

                                //更新提现状态
                                withDrawMapper.updateByPrimaryKeySelective(tempWd);
                                // 红包奖励
                                luckyMoneyHelper.openLuckyMoneyCouponIfNeed(withDraw.getUserId(),
                                    LuckyMonCouponConstant.CONDITION_TYPE_WITHDRAW_MONEY,
                                    null,false);
                                // 推送
                                jpushHelper.withDrawSuccessPush(String.valueOf(withDraw.getUserId()));

                            }
                            alipayOrder.setOrderId(response.getOrderId());
                            alipayOrder.setPayDate(response.getPayDate());
                            alipayOrder.setResponseCode(response.getCode());
                            alipayOrder.setResponseMsg(response.getMsg());
                            alipayOrder.setCreateTime(new Date());
                            alipayOrder.setBody(response.getBody());
                            alipayOrder.setSubCode(response.getSubCode());
                        }
                    }else{
                        alipayOrder.setOrderNo(orderNo);
                        alipayOrder.setResponseCode("5054");
                        alipayOrder.setResponseMsg("不能进行此次提现，提现状态："+withDraw.getStatus());
                        alipayOrder.setCreateTime(new Date());
                    }
                }else{
                    alipayOrder.setOrderNo(orderNo);
                    alipayOrder.setResponseCode("5053");
                    alipayOrder.setResponseMsg("提现表没有相应数据");
                    alipayOrder.setCreateTime(new Date());
                }
                alipayOrderMapper.insertSelective(alipayOrder);
                resOrders.add(alipayOrder);
            }catch (Exception e){
                logger.error("alipay transfer error : {}",e.toString());
                return resOrders;
            }
        }

        //判断是否需要批量修改订单状态为驳回
        if (transferReq.isBatchModifyOrderStatusReject()){
            List<AlipayOrder> alipayOrders = transferReq.getAlipayOrders();
            for (AlipayOrder alipayOrder: alipayOrders){
                WithDraw withDraw = withDrawMapper.selectByPrimaryKey(alipayOrder.getWithdrawId());

                if (!alipayOrder.getResponseCode().equals("10000")){
                    String reason = "打款失败";

                    withDrawMapper.updateOrderStatus(alipayOrder.getWithdrawId());
                    if(withDraw.getType().equals(WithDrawConstant.WITHDRAW_AMOUNT_TYPE)){
                        userMapper.plusUserAM(withDraw.getMoney(),withDraw.getUserId());
                    }
                    if(withDraw.getType().equals(WithDrawConstant.WITHDRAW_UIT_TYPE)){
                        userMapper.plusUserUit(DecimalUtil.convertMoneyToUit(withDraw.getMoney()),
                            withDraw.getUserId());
                    }
                    JpushSettings jpushSettings = jpushSettingsMapper.selectByType(JpushSettingsConstant.WITH_FAILED);
                    SendSmsResponse commonResponse = AliUtil.sendWithDrawSms(withDraw.getPhone(), withDraw.getUserName(), reason,
                            jpushSettings.getSmsSignName(),
                            jpushSettings.getSmsTemplateCode());
                    MobileCodeInformation information = informationHelper.getMobileCodeInformation(withDraw.getPhone(),
                            -1,jpushSettings.getSmsTemplateCode());
                    informationHelper.insertMobileCodeInformation(commonResponse,information);
                }
                userIncomeHelper.updateUserIncome(withDraw.getUserId(),3);
            }
        }

        return resOrders;
    }

    private void checkUserAmount(TransferReq transferReq){
        if(transferReq.isCheckLeftBeforeTransfer()){
            List<Long> ids = new ArrayList<>();
            for (AlipayOrder alipayOrder : transferReq.getAlipayOrders()){
                ids.add(alipayOrder.getWithdrawId());
            }
            List<WithdrawUserInfo> userInfos = userMapper.selectByWithDrawIds(ids);
            StringBuilder stringBuilder = new StringBuilder();
            boolean isBadResult = false;
            for(WithdrawUserInfo userInfo: userInfos){
                if(userInfo.getUserIntgeralTreasure() <0L){
                    isBadResult = true;
                    stringBuilder.append("用户:");
                    stringBuilder.append(userInfo.getUserNickName());
                    stringBuilder.append(" 集分宝小于0(");
                    stringBuilder.append(userInfo.getUserIntgeralTreasure());
                    stringBuilder.append(")");
                    stringBuilder.append("; ");
                    stringBuilder.append("<br/>");
                }
                if(userInfo.getUserAmount().compareTo(new BigDecimal(0))<0){
                    isBadResult = true;
                    stringBuilder.append("用户:");
                    stringBuilder.append(userInfo.getUserNickName());
                    stringBuilder.append(" 金额小于0(");
                    stringBuilder.append(userInfo.getUserAmount());
                    stringBuilder.append(")");
                    stringBuilder.append("; ");
                    stringBuilder.append("<br/>");
                }
            }
            if(isBadResult){
                stringBuilder.append("请谨慎打款");
                throw new BusinessException(stringBuilder.toString(),StatusCode.UIT_AM_NOT_ENOUGTH_WITHDRAW);
            }
        }
    }

    @Override
    public List<AlipayOrder> getAllTransferOrder() {
        return alipayOrderMapper.getAllTransferOrder();
    }

    @Override
    public List<AlipayOrder> getAllSuccessTransferOrder() {
        return alipayOrderMapper.getAllSuccessTransferOrder();
    }
}
